// index.js
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
const resolve = (...file) => path.resolve(__dirname, ...file)
const log = message => console.log(chalk.green(`${message}`))
const errorLog = error => console.log(chalk.red(`${error}`))
// 导入模板
const {
  vueTemplate,
  entryTemplate,
  jsonTemplate
} = require('./template')
// 生成文件
const generateFile = (path, data) => {
  if (fs.existsSync(path)) {
    errorLog(`${path}文件已存在`)
    return
  }
  return new Promise((resolve, reject) => {
    let index
    index = checkOS(path) ? path.lastIndexOf('/') : path.lastIndexOf('\\')
    let dir = path.substring(0, index + 1)
    if (fs.existsSync(dir)) {
      if (path.substring(path.lastIndexOf('.') + 1) === 'vue') {
        path = checkOS(path) ? toUpperCase(path, '/') : toUpperCase(path, '\\')
      }
      fs.writeFile(path, data, 'utf8', err => {
        if (err) {
          reject(err)
        } else {
          resolve(true)
        }
      })
    } else {
      fs.mkdir(dir, function (err) {
        if (!err) {
          if (path.substring(path.lastIndexOf('.') + 1) === 'vue') {
            path = checkOS(path) ? toUpperCase(path, '/') : toUpperCase(path, '\\')
          }
          fs.writeFile(path, data, 'utf8', err => {
            if (err) {
              reject(err)
            } else {
              resolve(true)
            }
          })
        }
      })
    }
  })
}
function mkdirsSync (dirname) {
  if (fs.existsSync(dirname)) {
    return true
  } else {
    if (mkdirsSync(path.dirname(dirname))) {
      fs.mkdirSync(dirname)
      return true
    }
  }
}
const checkOS = (path) => {
  let isMac = path.indexOf('\\') === -1
  return isMac
}
function toUpperCase(dirName, reg) {
  return dirName.substring(0, dirName.lastIndexOf(reg) + 1) + dirName.charAt(dirName.lastIndexOf(reg) + 1).toUpperCase() + dirName.slice(dirName.lastIndexOf(reg) + 2)
}
const checkName = (name) => {
  let num = 0
  while (name.indexOf('.') !== -1) {
    name = name.slice(name.indexOf('.') + 1)
    num += 1
  }
  return num
}
log('输入要生成的页面名称、会生成在 pages/目录下 多级页面请输入"/"字段分层级：例如：index/index-1')
let componentName = ''
process.stdin.on('data', async chunk => {
  // 组件名称
  let inputName = String(chunk).trim().toString()
  let prefix = inputName.substring(0, inputName.lastIndexOf('.'))
  let suffix = inputName.substring(inputName.lastIndexOf('.') + 1)
  if (inputName.indexOf('.') !== -1) {
    if (checkName(inputName) === 1) {
      if (suffix !== 'vue' && suffix !== 'js' && suffix !== 'json') {
        errorLog('请输入正确的vue文件后缀')
        return
      } else {
        let comPath = resolve('../../src/pages', inputName)
        if (fs.existsSync(comPath)) {
          log('该路径下文件已存在')
          return
        } else {
          let vueFileName
          if (inputName.indexOf('/') !== -1) {
            let dir = inputName.substring(0, inputName.lastIndexOf('/'))
            let dirPath = path.resolve(__dirname, '../../src/pages/' + dir)
            mkdirsSync(dirPath)
            componentName = inputName.substring(inputName.lastIndexOf('/') + 1, inputName.lastIndexOf('.'))
            vueFileName = componentName.charAt(0).toUpperCase() + componentName.slice(1)
            log(vueFileName)
          } else {
            componentName = inputName.substring(0, inputName.lastIndexOf('.'))
            vueFileName = componentName.charAt(0).toUpperCase() + componentName.slice(1)
            log(vueFileName)
          }
          log(`正在生成 vue 文件 ${prefix + '.vue'}`)
          await generateFile(resolve('../../src/pages', prefix + '.vue'), vueTemplate(vueFileName))
          log(`正在生成 entry 文件 ${prefix + '.js'}`)
          await generateFile(resolve('../../src/pages', prefix + '.js'), entryTemplate(componentName))
          log(`正在生成 json 文件 ${prefix + '.json'}`)
          await generateFile(resolve('../../src/pages', prefix + '.json'), jsonTemplate(componentName))
        }
      }
    } else {
      errorLog('文件整体路径只能有一个“.”符号')
      return
    }
  } else {
    if (fs.existsSync(resolve('../../src/pages', inputName))) {
      errorLog('该文件夹已存在')
      return
    } else {
      mkdirsSync(resolve('../../src/pages', inputName))
    }
  }

  process.stdin.emit('end')
})
process.stdin.on('end', () => {
  log('exit')
  process.exit()
})
